package edu.ustb.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSession;

import edu.ustb.domain.Address;
import edu.ustb.domain.Cart;
import edu.ustb.domain.Goods;
import edu.ustb.domain.User;
import edu.ustb.mapper.CartMapper;
import edu.ustb.service.AddressService;
import edu.ustb.service.AddressServiceImpl;
import edu.ustb.service.CartIndent;
import edu.ustb.service.CartIndentImpl;
import edu.ustb.utils.MybatisUtil;

//从商品详情直接跳转到订单页面
@WebServlet("/goodsToOrder.action")
public class GoodsToOrderController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	@SuppressWarnings("null")
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
		//设置请求数据的编码格式
		request.setCharacterEncoding("utf-8");
		User user = (User) request.getSession().getAttribute("user");
		int userId=user.getUserId();
		
		//获取购买商品的数量
		String itemNum = request.getParameter("addtoCartNum");
		//从表单获取goodsId
		String goodsId = request.getParameter("goodsId");
		
		CartIndent cartIndent=new CartIndentImpl();
		AddressService addressService = new AddressServiceImpl();
		
		Goods addgoods=new Goods();
		addgoods=cartIndent.findGoodsById(Integer.parseInt(goodsId));
		System.out.println(addgoods);
		List<Goods> goodsList2 =new ArrayList<Goods>();
		goodsList2.add(addgoods);
		List <Address> addressList =addressService.getAddress(userId);
		
		Cart addcart=new Cart();
		addcart.setItemGoods(Integer.parseInt(goodsId));
		addcart.setItemNum(Integer.parseInt(itemNum));
		addcart.setItemUser(userId);
	
		SqlSession openSession = MybatisUtil.open();
		CartMapper mapper = openSession.getMapper(CartMapper.class);

		//判断该商品是否已经在购物车中
		Cart cart=mapper.isGoodsInCart(Integer.parseInt(goodsId));
		if (cart==null){
			//如果购物车中没有该商品，就添加该商品和加入购物车的数量到shopitems表						
			int rows = mapper.addCart(addcart);		
		}else{
			//如果购物车已经有该商品，就直接修改数量
			cart.setItemNum(Integer.parseInt(itemNum));
			int rows = mapper.updateCart(cart);
		}
		//从购物车中获取该商品
		Cart addcart2=new Cart();
		addcart2 =mapper.isGoodsInCart(Integer.parseInt(goodsId));
		System.out.println(addcart2);	
		List<Cart> cartList2 =new ArrayList<Cart>(); 
		cartList2.add(addcart2);
		
		
		request.setAttribute("goodsList2", goodsList2);
		request.setAttribute("cartList2", cartList2);
		request.setAttribute("addressList", addressList);
		request.getRequestDispatcher("/Cart-indent.jsp").forward(request, response);
	}
}